/* eslint-disable no-debugger */
/* eslint-disable react/no-array-index-key */
/* eslint-disable jsx-a11y/label-has-associated-control */

/**
 * 表单项组件
 * @author LiAnqi
 * @date 2022-6-6
 * @description 封装FormItem，实现标签控件行内布局，可指定标签宽度、控件则自动填满，用于网格布局的表单。
 */

import { Form, Row, Col } from 'antd'
import { useState } from 'react'
import FieldControl from './FieldControl'
import { BROWSER_IS_IE } from '@commonMethod'
const wrapperCol = { span: 24 }

function FCGridFormItem(props) {
  const {
    name,
    label,
    labelWidth = '150px',
    children,
    fieldProps = { name },
    labelProps = {},
    controlProps = {},

    allowClear = true,
    onClear,
    showSearch = false,
    optionFilterProp = 'children',
    filterOption = (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
    ...restFieldProps
  } = props

  const { labelAlign, labelWrap, colon = true, ...restLabelProps } = labelProps || restFieldProps
  const selectRest = { allowClear, onClear, showSearch, optionFilterProp, filterOption }
  const requiredFilter = (fieldProps.rules || [])?.filter((rule) => rule.required)
  const required = restFieldProps.required || (requiredFilter && requiredFilter.length > 0)
  const labelClassName = `ant-form-item-no-colon ${required ? 'ant-form-item-required' : ''}${labelWrap ? 'ant-form-item-label-wrap' : ''
    }`
  const rLabel = label + (colon ? ' :' : '')

  const renderChildren = () => {
    // more than one child
    if (children && Array.isArray(children)) {
      return (
        <Row style={{ width: '100%' }} justify="start">
          {children?.map((item, index) => (
            <Col key={`c${index}`}>{item}</Col>
          ))}
        </Row>
      )
    }

    // one child
    if (typeof children === 'object') {
      return (
        <Row style={{ width: '100%' }} justify="start">
          <Col flex="auto">
            <Form.Item wrapperCol={wrapperCol} {...fieldProps} {...restFieldProps}>
              {children}
            </Form.Item>
          </Col>
        </Row>
      )
    }

    // Generate the child
    return (
      <Form.Item wrapperCol={wrapperCol} {...fieldProps} {...restFieldProps}>
        <FieldControl {...controlProps} {...restFieldProps} {...selectRest} />
      </Form.Item>
    )
  }

  // IE不需要span
  const [colSpan, setColSpan] = useState(BROWSER_IS_IE ? null : { span: 16 })
  // const [colSpan, setColSpan] = useState({ span: 16 })

  return (
    <Row style={{ width: '100%' }} justify="start">
      <Col
        // flex={labelWidth}
        span={8}
        offset={0}
        className="ant-col ant-form-item-label"
        style={{ textAlign: `${labelAlign}` }}
      >
        <label className={labelClassName}>{rLabel}</label>
      </Col>
      <Col {...colSpan} flex="auto">{renderChildren()}</Col>
      {/* {colSpan} */}
    </Row>
  )
}

export default FCGridFormItem
